package com.cgy.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cgy.entity.Chart;
import com.cgy.entity.ResStatistics;
import com.cgy.entity.ZiYuan;
import com.cgy.repository.ResStatisricsRepository;
import com.cgy.service.ResStatisticsService;
import com.cgy.service.ZiYuanService;

 
@CrossOrigin
@RestController
@RequestMapping("ResStatistics")
public class ResStatisticController {//统计图
	
	@Autowired 
	private ResStatisticsService resStatisticsService;
	@Autowired
	private ZiYuanService ziYuanService;
	
	@Autowired
	private ResStatisricsRepository  resStatisticsRepository;
	
	@GetMapping
	public Map<String, Object> findAllResZiYuan() {
		Map<String, Object> map = new HashMap<>();
		List<ZiYuan> findall = ziYuanService.findAllZiYuan();
		//创建储存资源室名称的集合 
		List<String> zname=new ArrayList<String>();
		for (int i = 0; i < findall.size(); i++) {
			zname.add(findall.get(i).getZname());
		} 
		map.put("zname", zname);
		//获取资源使用记录表的数据
		List<ResStatistics> findAllResStatistics = resStatisticsService.findAll();
		System.out.println(".size()"+findAllResStatistics.size());  
		//创建月份数组  
		String[] month = new String[findAllResStatistics.size()];
		ArrayList<String> arrayList = new ArrayList<String>();
		//遍历所有月份（有重复数据）
		for (int i = 0; i < findAllResStatistics.size(); i++) {
			 month[i] = findAllResStatistics.get(i).getMonth();
					 }
		//所有月份加入arraylist去重
	    for (String s:month) { 
		  if (!arrayList.contains(s)) {
			  arrayList.add(s);
	      } 
		}
		 
		map.put("month", arrayList);
		//创建chart类型数据数组
		List<Chart> cList = new ArrayList<>();
		for (int i = 0; i < findall.size(); i++) {//遍历资源室
			//data：创建储存资源室储存人次的集合
			List<Integer> data=new ArrayList<Integer>();
			for (int j = 0; j < arrayList.size(); j++) {//遍历月份
				System.out.println(arrayList.get(i));//根据机房id查询这个月数据
				Integer test = resStatisticsRepository.findTest(arrayList.get(j), findall.get(i).getZid());
				data.add(test);
			}
			cList.add(new Chart(findall.get(i).getZname(), "line", data));
		}
		map.put("cList", cList); 
		System.out.println(map);
		return map;
		
	}
	//添加
	@PostMapping
	public ResStatistics addresStatistics(ResStatistics r,Integer zid) {
		ZiYuan ziyuan = new ZiYuan();
		ziyuan.setZid(zid);
		r.setZiYuan(ziyuan);
		return resStatisticsService.addAndUpdateResStatistics(r);
	}
	

}
